Imports MIMS.WRS.Entities
Imports MIMS.WRS.Business
Imports System.Text
Imports MyFramework

Public Class MUKDetail
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents txtCon As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtOrderNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtReq As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlType As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtVessel As System.Web.UI.WebControls.TextBox
    Protected WithEvents chkDocRec As System.Web.UI.WebControls.CheckBox
    Protected WithEvents ddlBulk As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlSize As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlPayment As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlPack As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlSL As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtAccNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtCustomer As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtFinalDestination As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtArrivalPort As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtDescription As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtContainerNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtPISC As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnSubmit As System.Web.UI.WebControls.Button
    Protected WithEvents txtWeek As System.Web.UI.WebControls.TextBox
    Protected WithEvents CompareValidator2 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents ValidationSummary1 As System.Web.UI.WebControls.ValidationSummary
    Protected WithEvents Comparevalidator4 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents Comparevalidator5 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents ddlPayAuth As System.Web.UI.WebControls.DropDownList
    Protected WithEvents lblMessage As System.Web.UI.WebControls.Label
    Protected WithEvents RequiredFieldValidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents RequiredFieldValidator3 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtInvValue As System.Web.UI.WebControls.TextBox
    Protected WithEvents CompareValidator6 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents Requiredfieldvalidator4 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents Requiredfieldvalidator5 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents ddlPrimary As System.Web.UI.WebControls.DropDownList
    Protected WithEvents lblSuppOrderNo As System.Web.UI.WebControls.Label
    Protected WithEvents ltrNavigator As System.Web.UI.WebControls.Literal
    Protected WithEvents txtSInvoiced As System.Web.UI.WebControls.TextBox
    Protected WithEvents Comparevalidator7 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents chkOnHold As System.Web.UI.WebControls.CheckBox
    Protected WithEvents txtCustPONo As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlSupplier As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtPDepValue As System.Web.UI.WebControls.TextBox
    Protected WithEvents Comparevalidator1 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents txtSalesOrder As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents Comparevalidator3 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents Comparevalidator8 As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents txtSalesInvoiceValue As System.Web.UI.WebControls.TextBox
    Protected WithEvents chkArchived As System.Web.UI.WebControls.CheckBox
    Protected WithEvents txtLeadDays As System.Web.UI.WebControls.TextBox
    Protected WithEvents hidResponsibleHTML As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents txtFeederVessel As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlEstAct As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlNomShip As System.Web.UI.WebControls.DropDownList
    Protected WithEvents btnReqTextChange As System.Web.UI.WebControls.Button

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Protected WithEvents calOrderDate As DateTimePicker
    Protected WithEvents calPOInOpera As DateTimePicker
    Protected WithEvents calFactoryETD As DateTimePicker
    Protected WithEvents calTargetETD As DateTimePicker
    Protected WithEvents calShippedDate As DateTimePicker
    Protected WithEvents calETADate As DateTimePicker
    Protected WithEvents calConDel As DateTimePicker
    Protected WithEvents calSInvoicedPd As DateTimePicker
    Protected WithEvents calPPayDate As DateTimePicker
    Protected WithEvents calCompletedDate As DateTimePicker
    Protected WithEvents calSalesInvoiceDate As DateTimePicker
    Protected WithEvents calSalesPaymentDue As DateTimePicker


    Private ssr As ShippingStatusReport = Nothing

    Private ReadOnly Property IsAddNew() As Boolean
        Get
            If RequestContext.ShippingStatusReportID <= 0 Then
                Return True
            Else
                Return False
            End If
        End Get
    End Property

    Private ReadOnly Property SupplierOrderNumbers() As ArrayList
        Get
            If (Session("ChainOfID") Is Nothing _
                OrElse Convert.toString(Session("ChainOfID")) <> RequestContext.ChainOfID) Then
                Session("ChainOfID") = RequestContext.ChainOfID
                ' refresh the Supplier Order numbers list
                Dim i As Int32
                Dim alSON As ArrayList = New ArrayList

                For i = 0 To RequestContext.SelectedIDs.Count - 2
                    Dim id As Int32 = Convert.ToInt32(RequestContext.SelectedIDs(i))
                    Try
                        Dim obj As ShippingStatusReport = ShippingStatusReportService.GetShippingStatusReport(id)
                        alSON.Add(obj.SuppOrderNo)
                    Catch ex As Exception
                        alSON.Add("Failed:" + id.ToString())
                    End Try
                Next

                Session("SON") = alSON
            End If

            Return CType(Session("SON"), ArrayList)
        End Get
    End Property

    Private Sub BuildNavigator()
        Dim sb As StringBuilder = New StringBuilder

        If RequestContext.ChainOfID.Length > 0 Then
            Dim i As Int32
            ' RequestContext.SelectedIDs.Count always >= 2
            For i = 0 To RequestContext.SelectedIDs.Count - 2
                Dim id As String = Convert.toString(RequestContext.SelectedIDs(i))
                Dim suppOrderNo As String = Convert.toString(SupplierOrderNumbers(i))

                If (id.Equals(RequestContext.ShippingStatusReportID.ToString())) Then
                    sb.AppendFormat("<span class=""Selected"">[{0}]</span>", suppOrderNo)
                Else
                    sb.AppendFormat("<a href=""{0}"">[{1}]</a>", _
                        ResolveUrl(UrlBuilder.GetMUKDetailUrl(Integer.Parse(id), RequestContext.ChainOfID, False, RequestContext.Changed, RequestContext.OfficeID)), suppOrderNo)
                End If

                sb.Append("&nbsp;&nbsp;")
            Next
        Else
            sb.Append("<span class=""Selected"">[NEW RECORD]</span>")
        End If

        ltrNavigator.Text = sb.ToString()
    End Sub

    Private Function BuildObject() As Boolean
        If IsAddNew Then
            ssr = New ShippingStatusReport
        Else
            Try
                ssr = ShippingStatusReportService.GetShippingStatusReport(RequestContext.ShippingStatusReportID)

                If ssr Is Nothing Then
                    Throw New Exception
                End If
            Catch ex As Exception
                Me.lblMessage.Text = "Failed to load order. Order not found or has been deleted"
                Return False
                'Throw New Exception("Failed to load shipping report data", ex)
            End Try
        End If

        Return True
    End Function

    Public Shared Function GetWeek(ByVal inDate As Date) As Int32
        Dim wk As Int32 = DatePart(DateInterval.WeekOfYear, inDate, Microsoft.VisualBasic.FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFullWeek) ' DatePart(DateInterval.WeekOfYear, inDate.AddDays(-1))

        If wk > 52 Then
            wk = 52
        End If

        Return wk
    End Function


    'Private Function GetDate(ByVal inDate As DateTime) As DateTime
    '    If (inDate.Equals(DateTime.MinValue)) Then
    '        Return Nulls.NullDate
    '    Else
    '        Return inDate
    '    End If
    'End Function

    Protected Shared Function GetQueryInt(ByVal param As String) As Integer
        If HttpContext.Current.Request.QueryString(param) Is Nothing Then
            Return 0
        Else
            Try
                Return Integer.Parse(HttpContext.Current.Request.QueryString(param))
            Catch ex As Exception
                Return 0
            End Try
        End If
    End Function
    Public Shared ReadOnly Property REQ() As Integer
        Get
            If HttpContext.Current.Request.QueryString("req") <> Nothing Then
                Return GetQueryInt("req")
            Else
                Return 0
            End If
        End Get
    End Property

    Private Function BuildObjectForAddNewMode() As Boolean
        If IsAddNew Then
            Try
                If (REQ > 0) Then
                    ssr = ShippingStatusReportService.GetShippingStatusReportByReq(REQ)
                End If
            Catch ex As Exception
                Return False
            End Try
            Return True
        End If
        Return False
    End Function

    Private Sub UpdateData(ByVal bSave As Boolean)
        If (bSave) Then
            ssr.AccNo = txtAccNo.Text.Trim()
            ssr.ArrivalPort = txtArrivalPort.Text.Trim()
            ssr.BulkType = ddlBulk.SelectedItem.Value
            'Try
            '    ssr.BulkOrderNo = Integer.Parse(txtBKOrderNo.Text.Trim())
            'Catch
            '    ssr.BulkOrderNo = Null.NullInteger
            'End Try

            ssr.CompletedDate = calCompletedDate.SelectedValue
            ssr.ContainerNo = txtContainerNo.Text.Trim()
            ssr.ContainerSize = ddlSize.SelectedItem.Value
            ssr.ContainerDeliveried = calConDel.SelectedValue
            ssr.CustomerOrLocation = txtCustomer.Text.Trim()
            ssr.Description = txtDescription.Text.Trim()
            ssr.DocReceived = chkDocRec.Checked
            ssr.ETA = calETADate.SelectedValue
            ssr.FactoryETD = calFactoryETD.SelectedValue
            ssr.TargetETD = calTargetETD.SelectedValue
            ssr.FinalDestination = txtFinalDestination.Text.Trim()
            ssr.IsPrimary = ddlPrimary.SelectedItem.Value
            ssr.LP = ddlPack.SelectedItem.Value
            ssr.ModifiedDate = DateTime.Now
            ssr.OrderDate = calOrderDate.SelectedValue

            If (Security.IsAdmin) Then
                ssr.PayAuth = ddlPayAuth.SelectedItem.Value
            End If

            ssr.Payment = ddlPayment.SelectedItem.Value
            ssr.PI = txtPISC.Text.Trim()

            Try
                If txtCon.Text.Trim().Length > 0 Then
                    ssr.PONo_Consolidation = Integer.Parse(txtCon.Text.Trim())
                Else
                    ssr.PONo_Consolidation = Nulls.NullInteger
                End If
            Catch
                ssr.PONo_Consolidation = Nulls.NullInteger
            End Try

            Try
                If txtOrderNo.Text.Trim().Length > 0 Then ssr.PONo_Number = Integer.Parse(txtOrderNo.Text.Trim())
            Catch
                ssr.PONo_Number = Nulls.NullInteger
            End Try

            ssr.PONo_Supplier = ddlSupplier.SelectedItem.Value
            'Try
            '    ' update supplier here
            '    If txtSupp.Text.Trim().Length > 0 Then
            '        ssr.PONo_Supplier = Integer.Parse(txtSupp.Text.Trim())
            '    Else
            '        ssr.PONo_Supplier = Nulls.NullInteger
            '    End If
            'Catch
            '    ssr.PONo_Supplier = Nulls.NullInteger
            'End Try

            ssr.PONo_Type = ddlType.SelectedItem.Value
            Try
                If txtReq.Text.Trim().Length > 0 Then ssr.REQ = Integer.Parse(txtReq.Text.Trim())
            Catch
                ssr.REQ = Nulls.NullInteger
            End Try

            ssr.ShippingDate = calShippedDate.SelectedValue
            'ssr.ShippingLine = ddlSL.SelectedItem.Value
            ssr.Vessel = txtVessel.Text.Trim()

            If Not ssr.ETA = Nulls.NullDate Then
                ssr.Week = GetWeek(ssr.ETA)
            End If

            ssr.POInOpera = calPOInOpera.SelectedValue

            Try
                If txtInvValue.Text.Trim().Length > 0 Then
                    ssr.InvValue = Convert.ToDecimal(txtInvValue.Text)
                Else
                    ssr.InvValue = Nulls.NullDecimal
                End If
            Catch
                ssr.InvValue = Nulls.NullDecimal
            End Try

            ssr.PayDate = calPPayDate.SelectedValue

            ssr.SuppOrderNo = String.Format("{0}{1}", ssr.PONo_Supplier.ToString().PadLeft(3, "0"c), ssr.PONo_Number.ToString().PadLeft(3, "0"c))

            ssr.PONo_Office = Config.PONOOffice
            Try
                If txtSInvoiced.Text.Trim().Length > 0 Then
                    ssr.SInvoiced = Convert.ToInt32(txtSInvoiced.Text.Trim())
                Else
                    ssr.SInvoiced = Nulls.NullInteger
                End If
            Catch
                ssr.SInvoiced = Nulls.NullInteger
            End Try

            ssr.OnHold = chkOnHold.Checked

            ssr.OfficeID = RequestContext.OfficeID

            ssr.CustPONo = txtCustPONo.Text

            'ssr.BulkOrderOfficeID = Integer.Parse(ddlOffices.SelectedItem.Value)
            ssr.SInvoicedPd = calSInvoicedPd.SelectedValue
            'ssr.ConPoint = txtConPoint.Text.Trim()
            ssr.ShippingLineID = Integer.Parse(ddlSL.SelectedItem.Value)
            'ssr.ShippingLineCode = txtSLCode.Text.Trim()
            'ssr.ShippingLineUrl = txtSLUrl.Text
            'ssr.ConPointID = Integer.Parse(ddlConPoint.SelectedItem.Value)
            Try
                If txtPDepValue.Text.Trim().Length > 0 Then
                    ssr.PDepValue = Convert.ToDecimal(txtPDepValue.Text)
                Else
                    ssr.PDepValue = Nulls.NullDecimal
                End If
            Catch
                ssr.PDepValue = Nulls.NullDecimal
            End Try

            Try
                If txtSalesOrder.Text.Trim().Length > 0 Then ssr.SalesOrder = Integer.Parse(txtSalesOrder.Text.Trim())
            Catch
                ssr.SalesOrder = Nulls.NullInteger
            End Try
            Try
                If txtSalesInvoiceValue.Text.Trim().Length > 0 Then
                    ssr.SalesInvoiceValue = Convert.ToDecimal(txtSalesInvoiceValue.Text)
                Else
                    ssr.SalesInvoiceValue = Nulls.NullDecimal
                End If
            Catch
                ssr.InvValue = Nulls.NullDecimal
            End Try
            ssr.SalesInvoiceDate = calSalesInvoiceDate.SelectedValue
            ssr.SalesPaymentDue = calSalesPaymentDue.SelectedValue
            ssr.IsArchived = chkArchived.Checked

            Dim responsibleID As String = Request("ddlResponsible")
            If (responsibleID Is Nothing OrElse responsibleID.Length = 0) Then
                ssr.ResponsibleID = Nulls.NullInteger
            Else
                ssr.ResponsibleID = Convert.ToInt32(responsibleID)
            End If

            If (ssr.FactoryETD <> Nulls.NullDate AndAlso ssr.FactoryETDEnteredDate = Nulls.NullDate) Then
                ssr.FactoryETDEnteredDate = DateTime.Now
            End If

            ssr.FeederVessel = txtFeederVessel.Text.Trim
            ssr.IsNomShip = ddlNomShip.SelectedValue

            If (ddlEstAct.Enabled) Then
                ssr.EstActBlank = ddlEstAct.SelectedValue
            Else
                ssr.EstActBlank = ""
            End If
            If (calShippedDate.SelectedValue <> Nulls.NullDate AndAlso ddlEstAct.Items.Count = 3) Then
                ssr.EstActBlank = ddlEstAct.Items(2).Value
            End If
        Else
            Me.txtAccNo.Text = ssr.AccNo
            Me.txtArrivalPort.Text = ssr.ArrivalPort

            'If (ssr.BulkOrderNo <> Null.NullInteger) Then Me.txtBKOrderNo.Text = ssr.BulkOrderNo.ToString().PadLeft(6, "0"c)

            If (ssr.CompletedDate <> Nulls.NullDate) Then calCompletedDate.SelectedValue = ssr.CompletedDate

            If (ssr.PONo_Consolidation <> Nulls.NullInteger) Then Me.txtCon.Text = ssr.PONo_Consolidation.ToString()

            Me.txtContainerNo.Text = ssr.ContainerNo
            Me.txtCustomer.Text = ssr.CustomerOrLocation
            Me.txtDescription.Text = ssr.Description

            If (ssr.ETA <> Nulls.NullDate) Then calETADate.SelectedValue = ssr.ETA

            If (ssr.FactoryETD <> Nulls.NullDate) Then calFactoryETD.SelectedValue = ssr.FactoryETD
            If (ssr.TargetETD <> Nulls.NullDate) Then calTargetETD.SelectedValue = ssr.TargetETD

            Me.txtFinalDestination.Text = ssr.FinalDestination

            If (ssr.OrderDate <> Nulls.NullDate) Then calOrderDate.SelectedValue = ssr.OrderDate

            If (ssr.PONo_Number <> Nulls.NullInteger) Then Me.txtOrderNo.Text = ssr.PONo_Number.ToString().PadLeft(3, "0"c)

            Me.txtPISC.Text = ssr.PI

            If (ssr.REQ <> Nulls.NullInteger) Then Me.txtReq.Text = ssr.REQ.ToString()

            If (ssr.ShippingDate <> Nulls.NullDate) Then calShippedDate.SelectedValue = ssr.ShippingDate

            If (ssr.ContainerDeliveried <> Nulls.NullDate) Then calConDel.SelectedValue = ssr.ContainerDeliveried

            If (ssr.PONo_Supplier <> "") Then
                Try
                    ddlSupplier.SelectedIndex = ddlSupplier.Items.IndexOf(ddlSupplier.Items.FindByValue(ssr.PONo_Supplier))
                Catch ex As Exception

                End Try
            End If


            Me.txtVessel.Text = ssr.Vessel

            'Try
            '    Me.ddlSL.SelectedIndex = Me.ddlSL.Items.IndexOf(Me.ddlSL.Items.FindByValue(ssr.ShippingLine))
            'Catch ex As Exception
            'End Try

            Try
                Me.ddlPayment.SelectedIndex = Me.ddlPayment.Items.IndexOf(Me.ddlPayment.Items.FindByValue(ssr.Payment))
            Catch ex As Exception
            End Try

            Try
                Me.ddlBulk.SelectedIndex = Me.ddlBulk.Items.IndexOf(Me.ddlBulk.Items.FindByValue(ssr.BulkType))
            Catch ex As Exception
            End Try

            Try
                Me.ddlPack.SelectedIndex = Me.ddlPack.Items.IndexOf(Me.ddlPack.Items.FindByValue(ssr.LP))
            Catch ex As Exception
            End Try

            Try
                Me.ddlSize.SelectedIndex = Me.ddlSize.Items.IndexOf(Me.ddlSize.Items.FindByValue(ssr.ContainerSize))
            Catch ex As Exception
            End Try

            Try
                Me.ddlType.SelectedIndex = Me.ddlType.Items.IndexOf(Me.ddlType.Items.FindByValue(ssr.PONo_Type))
            Catch ex As Exception
            End Try

            If (Security.IsAdmin) Then
                Try
                    Me.ddlPayAuth.SelectedIndex = Me.ddlPayAuth.Items.IndexOf(Me.ddlPayAuth.Items.FindByValue(ssr.PayAuth))
                Catch ex As Exception
                End Try
            End If

            ddlPrimary.SelectedIndex = ddlPrimary.Items.IndexOf(ddlPrimary.Items.FindByValue(ssr.IsPrimary))

            chkDocRec.Checked = ssr.DocReceived

            If (ssr.Week <> Nulls.NullInteger) Then Me.txtWeek.Text = ssr.Week.ToString()

            If (ssr.POInOpera <> Nulls.NullDate) Then calPOInOpera.SelectedValue = ssr.POInOpera

            If (ssr.InvValue <> Nulls.NullDecimal) Then Me.txtInvValue.Text = ssr.InvValue.ToString(Config.DecimalFormat)

            If (ssr.PayDate <> Nulls.NullDate) Then calPPayDate.SelectedValue = ssr.PayDate

            Me.lblSuppOrderNo.Text = ssr.SuppOrderNo

            If (ssr.SInvoiced <> Nulls.NullInteger) Then Me.txtSInvoiced.Text = ssr.SInvoiced.ToString

            chkOnHold.Checked = ssr.OnHold

            txtCustPONo.Text = ssr.CustPONo

            'Try
            '    Me.ddlOffices.SelectedIndex = Me.ddlOffices.Items.IndexOf(Me.ddlOffices.Items.FindByValue(ssr.BulkOrderOfficeID.ToString()))
            'Catch ex As Exception

            'End Try
            If (ssr.SInvoicedPd <> Nulls.NullDate) Then calSInvoicedPd.SelectedValue = ssr.SInvoicedPd
            'txtCatalogue.Text = ssr.Catalogue
            Try
                ddlSL.SelectedIndex = ddlSL.Items.IndexOf(ddlSL.Items.FindByValue(ssr.ShippingLineID.ToString))
            Catch ex As Exception

            End Try


            'Try
            '    ddlConPoint.SelectedIndex = ddlConPoint.Items.IndexOf(ddlConPoint.Items.FindByValue(ssr.ConPointID.ToString))
            'Catch ex As Exception

            'End Try
            If (ssr.PDepValue <> Nulls.NullDecimal) Then Me.txtPDepValue.Text = ssr.PDepValue.ToString(Config.DecimalFormat)
            If (ssr.SalesOrder <> Nulls.NullInteger) Then txtSalesOrder.Text = ssr.SalesOrder.ToString()
            If (ssr.SalesInvoiceValue <> Nulls.NullDecimal) Then Me.txtSalesInvoiceValue.Text = ssr.SalesInvoiceValue.ToString(Config.DecimalFormat)
            If (ssr.SalesInvoiceDate <> Nulls.NullDate) Then calSalesInvoiceDate.SelectedValue = ssr.SalesInvoiceDate
            If (ssr.SalesPaymentDue <> Nulls.NullDate) Then calSalesPaymentDue.SelectedValue = ssr.SalesPaymentDue
            chkArchived.Checked = ssr.IsArchived
            If (ssr.LeadDays <> Nulls.NullInteger) Then txtLeadDays.Text = ssr.LeadDays.ToString()

            Try
                ddlNomShip.SelectedIndex = ddlNomShip.Items.IndexOf(ddlNomShip.Items.FindByValue(ssr.IsNomShip.ToString()))
            Catch ex As Exception

            End Try
            Try
                txtFeederVessel.Text = ssr.FeederVessel
                ddlEstAct.SelectedValue = ssr.EstActBlank
            Catch ex As Exception
            End Try

        End If
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Security.DenyIDSUser()

        AjaxPro.Utility.RegisterTypeForAjax(GetType(MIMS_WRS.Web.AjaxUtilMethod))
        txtReq.Attributes.Add("onchange", "javascript:return REQ_onchange();")

        If Not IsPostBack Then
            Response.Write("<div id='pleaseWait'>Please wait...</div>")
            Response.Flush()

            ' refresh parent if requested
            If (RequestContext.RefreshParent) Then
                Page.RegisterStartupScript("windowClose", "<script language='javascript'>windowCloseAndRefresh();</script>")
                'by pass all the remain process 
                'render only closing script
                Exit Sub
            End If

            BuildNavigator()

            'Added 06-Feb-2011
            If (REQ > 0) Then ' Add new mode, user change REQ field to load default data
                InitializeDataForNewMode()
                Return
            End If

            ' get list of available office for this user
            ' check security
            Dim col As OfficeCollection = OfficeService.GetOffices(RequestContext.CurrentUser.US_ID_PK)

            If (col.Count = 0) Then
                Throw New Exception("This user doesn't belong to any offices. Contact admin for more details.")
            End If

            'Me.ddlOffices.DataSource = OfficeService.GetOffices(OfficeColumns.OfficeID, OrderDirection.ASC)
            'Me.ddlOffices.DataTextField = OfficeColumns.OfficeCode.ToString()
            'Me.ddlOffices.DataValueField = OfficeColumns.OfficeID.ToString()
            'Me.ddlOffices.DataBind()

            'Me.ddlOffices.Items.Insert(0, New ListItem("", "-1"))
            ddlSL.DataSource = ShippingLineService.GetShippingLines(ShippingLineColumns.Abbr, OrderDirection.ASC)
            ddlSL.DataTextField = ShippingLineColumns.Abbr.ToString()
            ddlSL.DataValueField = ShippingLineColumns.ID.ToString()
            ddlSL.DataBind()
            ddlSL.Items.Insert(0, New ListItem("", Nulls.NullInteger.ToString()))

            ddlSupplier.DataSource = SupplierService.GetAllSuppliers()
            ddlSupplier.DataTextField = SupplierColumns.SupplierCode.ToString()
            ddlSupplier.DataValueField = SupplierColumns.SupplierCode.ToString()
            ddlSupplier.DataBind()
            ddlSupplier.Items.Insert(0, New ListItem("[--select supplier--]", "-1"))
            'ddlConPoint.DataSource = ConPointService.GetConPoints(ConPointColumns.Description, OrderDirection.ASC)
            'ddlConPoint.DataTextField = ConPointColumns.Description.ToString()
            'ddlConPoint.DataValueField = ConPointColumns.ConPointID.ToString()
            'ddlConPoint.DataBind()
            'ddlConPoint.Items.Insert(0, New ListItem("[add new -->]", Nulls.NullInteger.ToString()))

            If (IsAddNew) Then
                ' initalize value
                'txtReq.ReadOnly = True
                'txtSalesOrder.ReadOnly = True
                ' auto get the next req from system
                Me.txtReq.Text = ShippingStatusReportService.GetNextReqNumber(RequestContext.OfficeID).ToString()
                ' auto get the next sales order number from system
                'Me.txtSalesOrder.Text = ShippingStatusReportService.GetNextSalesOrderNumber().ToString()
                Me.btnSubmit.Text = "Create new order"

                '                Me.ddlOffices.SelectedIndex = Me.ddlOffices.Items.IndexOf(Me.ddlOffices.Items.FindByValue(RequestContext.OfficeID.ToString()))
                Me.txtLeadDays.Text = "N/A"
            Else
                Me.btnSubmit.Text = "Update order"

                If BuildObject() Then
                    Dim found As Boolean = False

                    For Each office As office In col
                        If ssr.OfficeID = office.OfficeID Then
                            found = True
                            Exit For
                        End If
                    Next

                    If Not found Then
                        Logger.Info(String.Format("Security WARNING: user {0} had attempt to invalid access order {1}", RequestContext.CurrentUser.US_ID_PK, RequestContext.ShippingStatusReportID))
                        Throw New Exception("Your request order doesn't belong to this user. Contact admin for more details.")
                    End If

                    UpdateData(False)

                    Dim supp As Supplier = SupplierService.GetSupplier(ssr.PONo_Supplier)
                    'Dim conPoint As conPoint = ConPointService.GetConPoint(supp.ConPointID)
                    Dim responsibles As ResponsibleCollection = ResponsibleService.GetResponsiblesByConPoint(supp.ConPointID)

                    Dim sb As StringBuilder = New StringBuilder
                    If responsibles.Count > 0 Then
                        sb.Append("<select name='ddlResponsible' id='ddlResponsible'>")
                        sb.Append("<option value=''>[--select responsible--]</option>")
                        For Each resp As Responsible In responsibles
                            If resp.ResponsibleID = ssr.ResponsibleID Then
                                sb.AppendFormat("<option selected value='{0}'>{1}</option>", resp.ResponsibleID, resp.Name)
                            Else
                                sb.AppendFormat("<option value='{0}'>{1}</option>", resp.ResponsibleID, resp.Name)
                            End If
                        Next
                        sb.Append("</select>")
                    Else
                        sb.Append("<i>[no responsible available]</i>")
                    End If


                    hidResponsibleHTML.Value = sb.ToString()
                End If
            End If
        End If
    End Sub

    Private Sub ReloadResponsible()
        Try
            Dim supp As Supplier = SupplierService.GetSupplier(ssr.PONo_Supplier)
            'Dim conPoint As conPoint = ConPointService.GetConPoint(supp.ConPointID)
            Dim responsibles As ResponsibleCollection = ResponsibleService.GetResponsiblesByConPoint(supp.ConPointID)

            Dim sb As StringBuilder = New StringBuilder
            If responsibles.Count > 0 Then
                sb.Append("<select name='ddlResponsible' id='ddlResponsible'>")
                sb.Append("<option value=''>[--select responsible--]</option>")
                For Each resp As Responsible In responsibles
                    If resp.ResponsibleID = ssr.ResponsibleID Then
                        sb.AppendFormat("<option selected value='{0}'>{1}</option>", resp.ResponsibleID, resp.Name)
                    Else
                        sb.AppendFormat("<option value='{0}'>{1}</option>", resp.ResponsibleID, resp.Name)
                    End If
                Next
                sb.Append("</select>")
            Else
                sb.Append("<i>[no responsible available]</i>")
            End If
            hidResponsibleHTML.Value = sb.ToString()
        Catch ex As Exception
        End Try
    End Sub
    Private Sub NavigateNext()
        Dim id As String = RequestContext.ShippingStatusReportID.ToString()
        Dim idx As Integer = RequestContext.SelectedIDs.IndexOf(id)

        ' the last item in RequestContext.SelectedIDs is a empty one
        ' by pass that item (Count - 2)
        If (idx < RequestContext.SelectedIDs.Count - 2) Then
            Response.Redirect(ResolveUrl(UrlBuilder.GetMUKDetailUrl(Convert.ToInt32(RequestContext.SelectedIDs(idx + 1)), RequestContext.ChainOfID, False, True, RequestContext.OfficeID)))
        Else
            Response.Redirect(ResolveUrl(UrlBuilder.GetMUKDetailUrl(Convert.ToInt32(id), RequestContext.ChainOfID, True, True, RequestContext.OfficeID)))
        End If
    End Sub

    Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        If Page.IsValid Then

            'If ddlBulk.SelectedIndex > 0 AndAlso txtBKOrderNo.Text.Trim.Length = 0 Then
            '    Me.lblMessage.Text = String.Format("You have selected '{0}' bulk type. Please input Bulk Order number", Me.ddlBulk.SelectedItem.Text)
            '    Return
            'End If

            If BuildObject() = False Then
                Return
            End If

            Dim oldETDDate As DateTime = ssr.FactoryETD
            Dim oldETADate As DateTime = ssr.ETA
            Dim oldShippedDate As DateTime = ssr.ShippingDate

            If IsAddNew Then
                ' re-get the next req from system
                'Me.txtReq.Text = ShippingStatusReportService.GetNextReqNumber(RequestContext.OfficeID).ToString()
                ' auto reget the next sales order number from system
                'Me.txtSalesOrder.Text = ShippingStatusReportService.GetNextSalesOrderNumber().ToString()
            End If
            UpdateData(True)

            If (Utilities.CompareDate(ssr.ContainerDeliveried, DateTime.Now) > 0) Then
                lblMessage.Text = "Container Delivery date cannot have a date greater than today's date."
                Return
            End If

            'If (ShippingStatusReportService.CheckUniqueSalesOrder(ssr.SalesOrder, ssr.REQ) > 0) Then
            '    lblMessage.Text = "Sales order has been used. Please enter another."
            '    Return
            'End If

            Dim saveCompleted As Boolean = False

            Try
                If IsAddNew Then
                    Dim result As Integer = ShippingStatusReportService.CheckReqConstraint(ssr)
                    If result = ECheckPOReqErrorCode.NoError Then
                        ShippingStatusReportService.CreateShippingStatusReport(ssr)
                        saveCompleted = True
                    Else
                        Dim errMsg As String = "The "
                        If (result And ECheckPOReqErrorCode.ConsolidationNotMatch) = ECheckPOReqErrorCode.ConsolidationNotMatch Then errMsg &= " Consolidation,"
                        If (result And ECheckPOReqErrorCode.ETADateNotMatch) = ECheckPOReqErrorCode.ETADateNotMatch Then errMsg &= " ETA Date,"
                        If (result And ECheckPOReqErrorCode.OrderTypeNotMatch) = ECheckPOReqErrorCode.OrderTypeNotMatch Then errMsg &= " Order type,"
                        If (result And ECheckPOReqErrorCode.TargetETDNotMatch) = ECheckPOReqErrorCode.TargetETDNotMatch Then errMsg &= " Target ETD,"
                        If (result And ECheckPOReqErrorCode.ShippedDateNotMatch) = ECheckPOReqErrorCode.ShippedDateNotMatch Then errMsg &= " Shipped date,"

                        If (result And ECheckPOReqErrorCode.NomShipNotMatch) = ECheckPOReqErrorCode.NomShipNotMatch Then errMsg &= " Nom Ship,"

                        If (result And ECheckPOReqErrorCode.EstActNotMatch) = ECheckPOReqErrorCode.EstActNotMatch Then errMsg &= " Est/Act,"

                        If (result And ECheckPOReqErrorCode.POInOperaNotMatch) = ECheckPOReqErrorCode.POInOperaNotMatch Then errMsg &= " PO In Opera ,"
                        If (result And ECheckPOReqErrorCode.PISCNotMatch) = ECheckPOReqErrorCode.PISCNotMatch Then errMsg &= " PI/SC,"
                        If (result And ECheckPOReqErrorCode.AccNoNotMatch) = ECheckPOReqErrorCode.AccNoNotMatch Then errMsg &= " Acc No,"
                        If (result And ECheckPOReqErrorCode.CustPONoNotMatch) = ECheckPOReqErrorCode.CustPONoNotMatch Then errMsg &= " Cust PO No,"
                        If (result And ECheckPOReqErrorCode.OnHoldNotMatch) = ECheckPOReqErrorCode.OnHoldNotMatch Then errMsg &= " On Hold,"
                        If (result And ECheckPOReqErrorCode.ArrivalPortNotMatch) = ECheckPOReqErrorCode.ArrivalPortNotMatch Then errMsg &= " Arrival Port,"
                        If (result And ECheckPOReqErrorCode.VesselNotMatch) = ECheckPOReqErrorCode.VesselNotMatch Then errMsg &= " Mother Vessel,"

                        If (result And ECheckPOReqErrorCode.FeederVesselNotMatch) = ECheckPOReqErrorCode.FeederVesselNotMatch Then errMsg &= " Feeder Vessel,"

                        If (result And ECheckPOReqErrorCode.ContainerNoNotMatch) = ECheckPOReqErrorCode.ContainerNoNotMatch Then errMsg &= " Container No,"
                        If (result And ECheckPOReqErrorCode.ContDelNotMatch) = ECheckPOReqErrorCode.ContDelNotMatch Then errMsg &= " Container Deliveried,"
                        If (result And ECheckPOReqErrorCode.DocsRecvNotMatch) = ECheckPOReqErrorCode.DocsRecvNotMatch Then errMsg &= " Docs Recv,"
                        If (result And ECheckPOReqErrorCode.CompletedNotMatch) = ECheckPOReqErrorCode.CompletedNotMatch Then errMsg &= " Completed date,"
                        If (result And ECheckPOReqErrorCode.SInvoiceNoNotMatch) = ECheckPOReqErrorCode.SInvoiceNoNotMatch Then errMsg &= " S Invoice No,"
                        If (result And ECheckPOReqErrorCode.SInvoicePDNotMatch) = ECheckPOReqErrorCode.SInvoicePDNotMatch Then errMsg &= " S Invoice PD,"
                        If (result And ECheckPOReqErrorCode.CustomerNotMatch) = ECheckPOReqErrorCode.CustomerNotMatch Then errMsg &= " Customer,"
                        If (result And ECheckPOReqErrorCode.FinalDestinationNotMatch) = ECheckPOReqErrorCode.FinalDestinationNotMatch Then errMsg &= " Final Destination,"
                        If (result And ECheckPOReqErrorCode.ShippingLineNotMatch) = ECheckPOReqErrorCode.ShippingLineNotMatch Then errMsg &= " Shipping Line,"
                        If (result And ECheckPOReqErrorCode.SalesOrderNotMatch) = ECheckPOReqErrorCode.SalesOrderNotMatch Then errMsg &= " Sales Order,"
                        If (result And ECheckPOReqErrorCode.ResponsibleNotMatch) = ECheckPOReqErrorCode.ResponsibleNotMatch Then errMsg &= " Responsible,"

                        errMsg = errMsg.Substring(0, errMsg.Length - 1)
                        lblMessage.Text = String.Format("{0} for requisition no.: {1} must be the same", errMsg, ssr.REQ)
                        ReloadResponsible()
                    End If
                Else
                    ShippingStatusReportService.UpdateShippingStatusReport(ssr)
                    saveCompleted = True
                End If
            Catch ex As MyFramework.BusinessException
                If (TypeOf (ex.InnerException) Is MyFramework.DataAccessException) Then
                    If (ex.InnerException.InnerException.Message.IndexOf("IX_ShippingStatusReport") > -1) Then
                        Me.lblMessage.Text = "The supplier number and order number has already existed. Please enter another."
                    Else
                        Me.lblMessage.Text = ex.InnerException.InnerException.Message
                    End If
                Else
                    Me.lblMessage.Text = ex.Message
                End If
                ReloadResponsible()
            Catch ex As Exception
                Me.lblMessage.Text = ex.Message
                ReloadResponsible()
            End Try

            If saveCompleted Then
                If IsAddNew Then
                    ' redirect to itself to add another and refresh the parent page
                    Response.Redirect(ResolveUrl(UrlBuilder.GetMUKDetailUrl(0, "", False, True, RequestContext.OfficeID)))
                Else
                    ' check for ETA or ETD has changed since its last first entry
                    Dim mail As FactoryDateChangedMail = New FactoryDateChangedMail
                    mail.POMUKNumber = ssr.SuppOrderNo

                    Try
                        If (oldETADate <> Nulls.NullDate AndAlso oldETADate.Equals(ssr.ETA) = False) Then
                            mail.OldDate = oldETADate.ToShortDateString()
                            mail.NewDate = ssr.ETA.ToShortDateString()
                            mail.DateType = "ETA"
                            mail.Send()
                        End If

                    Catch ex As Exception
                        Logger.Error("Failed to send FactoryDateChangedEmail", ex)
                        ReloadResponsible()
                    End Try

                    Try
                        If (oldETDDate <> Nulls.NullDate AndAlso oldETDDate.Equals(ssr.FactoryETD) = False) Then
                            mail.OldDate = oldETDDate.ToShortDateString()
                            mail.NewDate = ssr.FactoryETD.ToShortDateString()
                            mail.DateType = "Factory ETD"
                            mail.Send()
                        End If
                    Catch ex As Exception
                        Logger.Error("Failed to send FactoryDateChangedEmail", ex)
                        ReloadResponsible()
                    End Try

                    Try
                        If (oldShippedDate <> Nulls.NullDate AndAlso oldShippedDate.Equals(ssr.ShippingDate) = False) Then
                            Dim shippedDateChangedEmailObj As ShippedDateChangedMail = New ShippedDateChangedMail
                            shippedDateChangedEmailObj.POMUKNumber = ssr.SuppOrderNo
                            shippedDateChangedEmailObj.Send()
                        End If
                    Catch ex As Exception
                        Logger.Error("Failed to send ShippedDateChangedEmail", ex)
                        ReloadResponsible()
                    End Try

                    NavigateNext()
                End If
            End If
        End If
    End Sub

    Private Sub btnReqTextChange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReqTextChange.Click
        'Reload required fields that should be the same with existing REQ in the database in Add New mode
        '(Load default data, user no need to input the same fields manually)
        If IsAddNew Then
            Dim req As Int32 = Convert.ToInt32(txtReq.Text)
            If (req > 0) Then
                Response.Redirect(ResolveUrl(UrlBuilder.GetMUKDetailUrlForAddNewMode(req, True, RequestContext.OfficeID)))
            End If
        End If
    End Sub

    Private Sub InitializeDataForNewMode()
        If (BuildObjectForAddNewMode()) Then
            Try
                Me.btnSubmit.Text = "Create new order"

                ddlSL.DataSource = ShippingLineService.GetShippingLines(ShippingLineColumns.Abbr, OrderDirection.ASC)
                ddlSL.DataTextField = ShippingLineColumns.Abbr.ToString()
                ddlSL.DataValueField = ShippingLineColumns.ID.ToString()
                ddlSL.DataBind()
                ddlSL.Items.Insert(0, New ListItem("", Nulls.NullInteger.ToString()))

                ddlSupplier.DataSource = SupplierService.GetAllSuppliers()
                ddlSupplier.DataTextField = SupplierColumns.SupplierCode.ToString()
                ddlSupplier.DataValueField = SupplierColumns.SupplierCode.ToString()
                ddlSupplier.DataBind()
                ddlSupplier.Items.Insert(0, New ListItem("[--select supplier--]", "-1"))

                Dim found As Boolean = False
                Dim col As OfficeCollection = OfficeService.GetOffices(RequestContext.CurrentUser.US_ID_PK)

                If (col.Count = 0) Then
                    Return
                End If
                For Each office As office In col
                    If ssr.OfficeID = office.OfficeID Then
                        found = True
                        Exit For
                    End If
                Next
                If Not found Then
                    Return
                End If

                LoadDefaultDataForAddNewMode()

                Dim supp As Supplier = SupplierService.GetSupplier(ssr.PONo_Supplier)
                'Dim conPoint As conPoint = ConPointService.GetConPoint(supp.ConPointID)
                Dim responsibles As ResponsibleCollection = ResponsibleService.GetResponsiblesByConPoint(supp.ConPointID)

                Dim sb As StringBuilder = New StringBuilder
                If responsibles.Count > 0 Then
                    sb.Append("<select name='ddlResponsible' id='ddlResponsible'>")
                    sb.Append("<option value=''>[--select responsible--]</option>")
                    For Each resp As Responsible In responsibles
                        If resp.ResponsibleID = ssr.ResponsibleID Then
                            sb.AppendFormat("<option selected value='{0}'>{1}</option>", resp.ResponsibleID, resp.Name)
                        Else
                            sb.AppendFormat("<option value='{0}'>{1}</option>", resp.ResponsibleID, resp.Name)
                        End If
                    Next
                    sb.Append("</select>")
                Else
                    sb.Append("<i>[no responsible available]</i>")
                End If
                hidResponsibleHTML.Value = sb.ToString()
            Catch ex As Exception
            End Try
        End If
    End Sub
    Private Sub LoadDefaultDataForAddNewMode()
        Try
            txtReq.Text = ssr.REQ.ToString()
            If (ssr.SalesOrder <> Nulls.NullInteger) Then txtSalesOrder.Text = ssr.SalesOrder.ToString()
            If (ssr.PONo_Consolidation <> Nulls.NullInteger) Then Me.txtCon.Text = ssr.PONo_Consolidation.ToString()

            Try
                Me.ddlType.SelectedIndex = Me.ddlType.Items.IndexOf(Me.ddlType.Items.FindByValue(ssr.PONo_Type))
            Catch ex As Exception
            End Try

            If (ssr.ETA <> Nulls.NullDate) Then calETADate.SelectedValue = ssr.ETA

            If (ssr.ShippingDate <> Nulls.NullDate) Then calShippedDate.SelectedValue = ssr.ShippingDate

            If (ssr.TargetETD <> Nulls.NullDate) Then calTargetETD.SelectedValue = ssr.TargetETD

            Try
                ddlNomShip.SelectedIndex = ddlNomShip.Items.IndexOf(ddlNomShip.Items.FindByValue(ssr.IsNomShip.ToString()))
            Catch ex As Exception
            End Try

            Try
                txtFeederVessel.Text = ssr.FeederVessel
                ddlEstAct.SelectedValue = ssr.EstActBlank
            Catch ex As Exception
            End Try

            If (ssr.POInOpera <> Nulls.NullDate) Then calPOInOpera.SelectedValue = ssr.POInOpera
            Me.txtPISC.Text = ssr.PI
            Me.txtAccNo.Text = ssr.AccNo
            txtCustPONo.Text = ssr.CustPONo
            chkOnHold.Checked = ssr.OnHold
            Me.txtArrivalPort.Text = ssr.ArrivalPort
            Me.txtVessel.Text = ssr.Vessel
            Me.txtContainerNo.Text = ssr.ContainerNo
            If (ssr.ContainerDeliveried <> Nulls.NullDate) Then calConDel.SelectedValue = ssr.ContainerDeliveried
            If (ssr.CompletedDate <> Nulls.NullDate) Then calCompletedDate.SelectedValue = ssr.CompletedDate
            If (ssr.SInvoiced <> Nulls.NullInteger) Then Me.txtSInvoiced.Text = ssr.SInvoiced.ToString
            If (ssr.SInvoicedPd <> Nulls.NullDate) Then calSInvoicedPd.SelectedValue = ssr.SInvoicedPd
            Me.txtCustomer.Text = ssr.CustomerOrLocation
            Me.txtFinalDestination.Text = ssr.FinalDestination
            Try
                ddlSL.SelectedIndex = ddlSL.Items.IndexOf(ddlSL.Items.FindByValue(ssr.ShippingLineID.ToString))
            Catch ex As Exception
            End Try

            If (ssr.SalesOrder <> Nulls.NullInteger) Then txtSalesOrder.Text = ssr.SalesOrder.ToString()
            If (ssr.PONo_Number <> Nulls.NullInteger) Then Me.txtOrderNo.Text = ssr.PONo_Number.ToString().PadLeft(3, "0"c)
            If (ssr.OrderDate <> Nulls.NullDate) Then calOrderDate.SelectedValue = ssr.OrderDate
            If (ssr.PONo_Supplier <> "") Then
                Try
                    ddlSupplier.SelectedIndex = ddlSupplier.Items.IndexOf(ddlSupplier.Items.FindByValue(ssr.PONo_Supplier))
                Catch ex As Exception
                End Try
            End If
        Catch ex As Exception
        End Try
    End Sub
End Class
